package com.cennavi.bigdata.baotou.scripts;

import com.alibaba.fastjson.JSONObject;
import com.cennavi.bigdata.baotou.util.PropertiesUtil;
import com.mongodb.*;
import org.bson.types.ObjectId;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zuoweiguang on 2017/3/9.
 * 脚本
 * 分析决策支持系统：指数分析预警 - 根据商圈的坐标点生成区域几何坐标，存入exponent_region表中
 * 再根据商圈区域到rtic_centroid表中，匹配范围内的所有rtic中心点，将获取到的点存入exponent_region表中
 *
 */
public class MakeExponentRegion {

    public SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
    private MongoClient mongoClient = null;
    private DB db = null;
    private DBCollection exponentRegionCol = null;
    private DBCollection rticCentroidCol = null;

    public MakeExponentRegion() {
        //获取 mongo 的连接
        ServerAddress serverAddress = new ServerAddress("15.32.12.63", 27017);
        mongoClient = new MongoClient(serverAddress);
        db = mongoClient.getDB("baotou_traffic");
        exponentRegionCol = db.getCollection("exponent_region");
        rticCentroidCol = db.getCollection("rtic_centroid");
    }

    /**
     * 根据商圈、学校、医院、政府、公园、地铁的位置，生成范围区域
     */
    public void makeRegionByLocation() {

        try {
            DBCursor cursor = exponentRegionCol.find();
            while (cursor.hasNext()) {
                try {
                    DBObject data = cursor.next();
                    ObjectId id = (ObjectId) data.get("_id");
                    System.out.println(id.toString());
                    Double offset = (Double) data.get("offset");
                    DBObject location = (DBObject) data.get("location");
//                    System.out.println(location.toString());
                    List<Double> coordinates = (List<Double>) location.get("coordinates");
                    double lon = coordinates.get(0);
                    double lat = coordinates.get(1);
//                    System.out.println(lon + "," + lat);
                    JSONObject geojson = createFirstPolygon(lon, lat, offset);
                    System.out.println(geojson);

                    /**
                     * 根据生成好的区域，到rtic_centroid表中匹配rtic
                     * db.places.find( { coordinate : { $geoWithin : { $polygon : [
                     [121.45183 , 31.243816] ,
                     [121.533181, 31.24344] ,
                     [121.535049, 31.208983] ,
                     [121.448955, 31.214913] ,
                     [121.440619, 31.228748]
                     ] } } } )
                     */
                    List<String> rticList = new ArrayList<>();
                    List regionCoordinates = (List) geojson.get("coordinates");
                    regionCoordinates = (List) regionCoordinates.get(0);
                    BasicDBObject query = new BasicDBObject();
                    query.append("rtic_centroid", new BasicDBObject("$geoWithin", new BasicDBObject("$polygon", regionCoordinates)));
                    DBCursor cursor1 = rticCentroidCol.find(query);
                    while (cursor1.hasNext()) {
                        DBObject rticCentroidObj = cursor1.next();
                        String rtic_id = (String) rticCentroidObj.get("rtic_id");
                        rticList.add(rtic_id);
                    }

                    //更新region字段，同时存入匹配到的rtic
                    DBObject condition = new BasicDBObject();
                    condition.put("_id", id);
                    BasicDBObject updateObj = new BasicDBObject();
                    updateObj.append("region", geojson);
                    updateObj.append("rtic", rticList);
                    exponentRegionCol.update(condition, new BasicDBObject("$set", updateObj));

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mongoClient.close();
        }
    }

    //根据前端传来的坐标，创建第一个polygon
    private JSONObject createFirstPolygon(double longitude, double latitude, double offset) {
        List<List> brackets = new ArrayList<>();
        List<List> coordinatesNew = new ArrayList<>(5);

        List<Double> coordinate1 = new ArrayList<>(2);
        coordinate1.add(longitude - offset);
        coordinate1.add(latitude + offset);
        coordinatesNew.add(coordinate1);

        List<Double> coordinate2 = new ArrayList<>(2);
        coordinate2.add(longitude + offset);
        coordinate2.add(latitude + offset);
        coordinatesNew.add(coordinate2);

        List<Double> coordinate3 = new ArrayList<>(2);
        coordinate3.add(longitude + offset);
        coordinate3.add(latitude - offset);
        coordinatesNew.add(coordinate3);

        List<Double> coordinate4 = new ArrayList<>(2);
        coordinate4.add(longitude - offset);
        coordinate4.add(latitude - offset);
        coordinatesNew.add(coordinate4);

        List<Double> coordinate5 = new ArrayList<>(2);
        coordinate5.add(longitude - offset);
        coordinate5.add(latitude + offset);
        coordinatesNew.add(coordinate5);
        brackets.add(coordinatesNew);
        JSONObject firstPolygonGeojson = createPolygonGeojson(brackets);

        return firstPolygonGeojson;
    }


    //根据传入的polygon坐标数组，组合geojson
    private JSONObject createPolygonGeojson(List<List> coordinates) {
        JSONObject geojson = new JSONObject();
        geojson.put("type", "Polygon");
        geojson.put("coordinates", coordinates);
        return geojson;
    }

    public static void main(String[] args) {
        MakeExponentRegion mer = new MakeExponentRegion();
        mer.makeRegionByLocation();
    }

}
